package com.microservice.user.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.microservice.user.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 用户Mapper
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    /**
     * 查询用户角色列表
     * 通过 sys_user_role 和 sys_role 表关联查询
     */
    @Select("SELECT r.role_code FROM sys_user_role ur " +
            "INNER JOIN sys_role r ON ur.role_id = r.id " +
            "WHERE ur.user_id = #{userId} AND r.status = 1")
    List<String> selectUserRoles(Long userId);
    
    /**
     * 查询用户权限列表
     * 通过 sys_user_role, sys_role_permission 和 sys_permission 表关联查询
     */
    @Select("SELECT DISTINCT p.permission_code FROM sys_user_role ur " +
            "INNER JOIN sys_role_permission rp ON ur.role_id = rp.role_id " +
            "INNER JOIN sys_permission p ON rp.permission_id = p.id " +
            "WHERE ur.user_id = #{userId} AND p.status = 1")
    List<String> selectUserPermissions(Long userId);
    
    /**
     * 为新注册用户分配默认角色（普通用户）
     * 假设普通用户角色的role_code为'USER'，需要先查询该角色的ID再插入
     */
    @Insert("INSERT INTO sys_user_role (user_id, role_id, create_time) " +
            "SELECT #{userId}, id, NOW() FROM sys_role " +
            "WHERE role_code = 'ROLE_USER' AND status = 1 LIMIT 1")
    void insertDefaultUserRole(Long userId);
}
